// 安装阶段：缓存指定的资源
self.addEventListener('install', event => {
  console.log(111111)
  console.log(caches)
  event.waitUntil(
    caches.open('my-cache-v1').then(cache => {
      return cache.addAll([
        '/',
        '/index.html',
        '/styles.css',
        '/script.js',
        '/image.png'
      ]);
    })
  );
});

// 拦截请求并尝试从缓存中获取响应
self.addEventListener('fetch', event => {
  console.log(222222)
  console.log(caches)
  console.log(event)
  event.respondWith(
    caches.match(event.request).then(response => {
      console.log(response)
      // 如果缓存中有匹配的响应，直接返回
      if (response) {
        return response;
      }
      // 否则从网络获取
      return fetch(event.request);
    })
  );
});

// 激活阶段：处理缓存版本更新
self.addEventListener('activate', event => {
  const cacheWhitelist = ['my-cache-v1'];
  console.log(333333)
  console.log(caches)
  event.waitUntil(
    caches.keys().then(cacheNames => {
      return Promise.all(
        cacheNames.map(cacheName => {
          if (!cacheWhitelist.includes(cacheName)) {
            return caches.delete(cacheName);
          }
        })
      );
    })
  );
});